package com.lgmshare.component.utils.thread;

import android.os.Looper;

import com.lgmshare.component.annotation.PluginApi;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: lim
 * @ClassName: ThreadPool
 * @description: 开启一个线程来执行UI之外的耗时操作
 * @Email lgmshare@gmail.com
 * @datetime 2014-11-4 下午1:09:14
 */
public class ThreadPool {

    private static final String TAG = "ThreadPool";

    private static final int CORE_POOL_SIZE = 4;  // 线程池的大小最好设置成为<CUP核数*2>
    private static final int MAX_POOL_SIZE = 8;   // 设置线程池的最大线程数
    private static final int KEEP_ALIVE_TIME = 10;// 设置线程的存活时间

    private final Executor mExecutor;

    public static ThreadPool getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * 类级的内部类，也就是静态的成员式内部类，该内部类的实例与外部类的实例没有绑定关系，
     * 而且只有被调用到才会装载，从而实现了延迟加载
     */
    private static class InstanceHolder {
        /**
         * 静态初始化器，由JVM来保证线程安全
         */
        public static final ThreadPool INSTANCE = new ThreadPool();
    }

    @PluginApi
    public ThreadPool() {
        this(TAG, CORE_POOL_SIZE, MAX_POOL_SIZE);
    }

    @PluginApi
    public ThreadPool(String name, int coreSize, int maxSize) {
        //this(name, coreSize, maxSize, new PriorityBlockingQueue<Runnable>());
        this(name, coreSize, maxSize, new LinkedBlockingDeque<Runnable>());
    }

    /**
     * @param name
     * @param coreSize 线程池的大小
     * @param maxSize  最大线程数
     * @param queue    工作队列
     */
    @PluginApi
    public ThreadPool(String name, int coreSize, int maxSize, BlockingQueue<Runnable> queue) {
        if (coreSize <= 0) {
            coreSize = 1;
        }
        if (maxSize <= coreSize) {
            maxSize = coreSize;
        }
        // 创建线程池工厂
        ThreadFactory factory = new PriorityThreadFactory(name, android.os.Process.THREAD_PRIORITY_BACKGROUND);
        mExecutor = new ThreadPoolExecutor(coreSize, maxSize, KEEP_ALIVE_TIME, TimeUnit.SECONDS, queue, factory);
    }

    public void runTask(final Runnable runnable) {
        mExecutor.execute(runnable);
    }


    public void removeTask(final Runnable runnable) {
    }

    @PluginApi
    public static void runOnAsyncTask(final Runnable runnable) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            getInstance().runTask(runnable);
        } else {
            runnable.run();
        }
    }
}